package com.scy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.scy.common.Result;
import com.scy.dto.params.LoginParam;
import com.scy.entity.User;
import com.scy.service.LoginService;
import com.scy.service.UserService;
import com.scy.utils.JWTUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 本类用来演示
 *
 * @author wwh
 * @date 2024/7/5 8:56 $
 */
@Service
public class LoginServiceImpl implements LoginService {

    public static final String  slat = "ak^%$2H1&";

    @Resource
    UserService userService;
    @Resource
    RedisTemplate<String,String> redisTemplate;
    @Override
    public Result login(LoginParam loginParam) throws Exception {

        //取出所需要的参数值
        String account = loginParam.getUsername();
        String password = loginParam.getPassword();

        //判断空值
        if (StringUtils.isBlank(account)|| StringUtils.isBlank(password)){
            return Result.fail(10001,"参数有误");
        }
        //一切的密码都不会放在明文中,对密码进行加密
        String pwd = DigestUtils.md5Hex(password + slat);

        /*数据库表中本来就是加密后的值了,所有,我必须加密跟他去对比才能判断*/
        User user = userService.findUser(account,pwd);

        if (user == null){
            return Result.fail(10002,"用户信息有误");
        }
        //登录成功，使用JWT生成token，返回token和redis中

        //返回的是对象
        //用fastjson将object类型转为map
        String userJson = JSON.toJSONString(user);

        String token = JWTUtils.generateToken(JSON.parseObject(userJson, Map.class),null,1000000);

        //放入redis中,用作验证中心
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return Result.ok("ok",token);
    }

    @Override
    public User checkToken(String token) {

        /*判空*/
        if (StringUtils.isBlank(token)){
            return null;
        }

        Map<String, Object> infoFromToken;

        try {

            /*验证*/
          infoFromToken= JWTUtils.getInfoFromToken(token, null);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (infoFromToken == null){
            return null;
        }
        /*去redis查看,是否存在*/
        String userJson = redisTemplate.opsForValue().get("TOKEN"+token);
        if (StringUtils.isBlank(userJson)){
            return null;
        }

        return JSON.parseObject(token,User.class);

    }

}
